package com.hra.logger;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.hra.logger.utils.Utils;

public class BootCompleteReceiver extends BroadcastReceiver {
    private static final String TAG = "BootCompleteReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            if (Utils.DEBUG) {
                Log.i(TAG, "Received BOOT_COMPLETED broadcast");
            }
            startLoggingAfterBoot(context);
        }
    }

    private void startLoggingAfterBoot(Context context) {
        try {
            SharedPreferences sharedPreferences = context.getSharedPreferences(Utils.PRE_STATE_NAME, Context.MODE_PRIVATE);
            // Activate all log types that were enabled before shutdown
            for (int logType : Utils.LOG_TYPES) {
                if (sharedPreferences.getBoolean(Utils.getLogTypeName(logType), Utils.FIRST_BOOT_COMPLETE_AUTO_START)) {
                    Log.i(TAG, "Reboot starting logging for: " + Utils.getLogTypeName(logType));
                    Intent startIntent = new Intent(context, LoggingService.class);
                    startIntent.setAction(Utils.ACTION_START_LOGGING);
                    startIntent.putExtra(Utils.KEY_LOG_TYPE, logType);
                    context.startForegroundService(startIntent);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error starting logging after boot", e);
        }
    }
}